# coding=utf-8
from urllib.parse import urlparse
from myselenium import *
import sys
from apiajax import *
global Price
global user  #全局的手机账号
global url  #全局的地址
sys.setrecursionlimit(999999999)  #10000为设置的栈大小
# 判断是否有购买按钮
def buyBtnClick(driver):
    global user
    global Price
    global url
    i = 1
    while i < 10000000:
        i = i + 1
        Price = to_int(getGoodINIPrice())
        url = getGoodINIUrl()
        driver.get(url)
        time.sleep(1)
        if valclass(driver, 'van-goods-action-button--last') == False:
            print('没有找到立即购买按钮')
        else:
            if bhzfc(valclass(driver, 'van-goods-action-button--last'), '立即购买'):
                tapclass(driver, 'van-goods-action-button--last')
                shopNextBtnClick(driver)
            else:
                btntxt = valclass(driver, 'van-goods-action-button--last')
                msg = "无法购买，原因：[" + btntxt + ']'
                if btntxt == '已达最大限购数量':
                    print(msg)
                    print('程序将在十分钟后退出')
                    break
                else:
                    print(currentTime() + msg)
                    savelog(msg)

#点购物的下一步
def shopNextBtnClick(driver):
    print('准备点击下一步')
    i = 1
    while i < 10000000:
        i = i + 1
        try:
            if valclass(driver, 'van-button--danger') != False:
                if valclass(driver, 'van-button--danger') != '':
                    print(valclass(driver, 'van-button--danger'))
                    tapclass(driver, 'van-button--danger')
                    shopping(driver)
                    break
        except:
            print('没有找到下一步按钮')
#直接进入订单页面
def shopping(driver):
    global user
    global Price
    global url
    i = 1
    while i < 10000:
        i= i+1
        Price = to_int(getGoodINIPrice())
        if valclass(driver, 'error-msg') != False:  #判断订单页面是否过期
            print('订单页面过期')
            break
        try:
            if (valhtml(driver, 'h2') == '没有可以购买的商品'):
                print('没有可以购买的商品，价格为0了，重新刷新网页')
                driver.refresh()
            else:
                time.sleep(0.3)
                if valclass(driver, 'new-submit-bar__price--padding') != False:
                    print('获取价格中...')
                    num = valclass(driver, 'new-submit-bar__price--padding')
                    num = to_int(num)
                    print("当前商品价格是" + str(num) + ' 您想购买的价格是' + str(to_int(Price)))
                    if num <= to_int(Price):
                        shop = valclass(driver,'new-goods-list-card__title') #商品标题
                        tapclass(driver, 'van-submit-bar__button--danger')
                        time.sleep(3)
                        if ifclass(driver, 'zan-pay__main--a'):
                            print('开始下单')
                            time.sleep(0.1)
                            tapclass(driver, 'zan-pay__method-content--alipay_wap')
                            time.sleep(3)
                            alipayurl = driver.current_url
                            successlog(user + '\r\n' + alipayurl)
                            post("index.php/api/alipayurl/add",{'shopname':shop,'amount':num,'phone':user,'alipayurl':alipayurl})#提交给app去支付
                            print('下单完成了哦,赶快去付款把！！！')
                            time.sleep(5)
                            break
                        else:
                            print('下单失败，没有找到支付的按钮')
                            driver.refresh()
                    else:
                        print('预期价格未达到')
                        driver.refresh()
        except:
            time.sleep(0.1)

def getLoginUser():
    #phone = sys.argv[1]
    phone = '19986287991'   # debug
    return os.path.realpath('.') + "\\gooleUser\\" + phone

    # userConfList = []
    # with open('loginuser_conf.txt', 'r') as f:
    #     userConfList = f.readlines()
    #     print(userConfList)
    #     u = str(sys.argv[1])
    #     i = int(u)
    #     user = str(userConfList[i - 1])
    #     user_data = os.path.realpath('.') + str(userConfList[i - 1])
    #     return user_data

#个人中心
def openWscUser(driver):
    driver.get(getGoodINIUrl())
    time.sleep(0.5)
    # 新开一个窗口，通过执行js来新开一个窗口
    windows = driver.window_handles

    _goodsUrl = driver.current_url;
    parsed = urlparse(_goodsUrl)

    _goodsUrl = 'https://' + parsed.netloc + "/wscuser/membercenter"
    js = 'window.open("%s");' % _goodsUrl
    js = js.replace("\r", "")
    js = js.replace("\n", "")
    #print(js)
    driver.execute_script(js)
    driver.switch_to.window(windows[-1])
    return


def main():
    global user
    global Price
    global url

    option = webdriver.ChromeOptions()
    option.add_argument('--ignore-certificate-errors')
    option.add_argument('--ignore-ssl-errors')
    user_data = getLoginUser()
    option.add_argument(r'--user-data-dir=' + user_data)
    prefs = {"profile.managed_default_content_settings.images": 2}
    option.add_experimental_option("prefs", prefs)
    driver = webdriver.Chrome(chrome_options=option)
    driver.set_window_size(300,450)
    # driver.minimize_window()
    openWscUser(driver)

    driver.get('https://shop91091478.youzan.com/wscuser/membercenter/setting')
    time.sleep(2)
    user = str(driver.find_elements("css selector", ".van-ellipsis")[0].text)
    i = 1
    Price = to_int(getGoodINIPrice())
    url = getGoodINIUrl()
    print(str(user))
    print(str(url))
    print(str(Price))
    while i < 6000:
        i = i + 1
        buyBtnClick(driver)

main()
